<template>
  <div class="app-container">
    <span style="font-size: medium;color: rgba(151,170,195) "> / 采购订单 / 订单维护</span>

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="85px" style="margin-top: 20px">
      <el-form-item label="订单编号" prop="orderNo">
        <el-input
            v-model="queryParams.orderNo"
            placeholder="请输入采购订单编号"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供货商名称" prop="companyName">
        <el-input
            v-model="queryParams.companyName"
            placeholder="请输入供货商名称"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable>
          <el-option
              v-for="dict in purchase_order_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
        >删除采购订单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderMaintainList" @selection-change="handleSelectionChange"
              style="margin-top: 15px">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="采购订单编号" fixed align="center" prop="orderNo" width="125">
        <template #default="scope">
          <router-link :to="'/OrderDetail/index/' + scope.row.orderNo" class="link-type">
            <span>{{ scope.row.orderNo }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="供货商名称" align="center" prop="companyName" width="120"/>
      <el-table-column label="下单时间" align="center" prop="orderTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="负责人" align="center" prop="responsiblePerson" width="100"/>
      <el-table-column label="修改人" align="center" prop="modifiedBy" width="100"/>
      <el-table-column label="修改日期" align="center" prop="modifiedDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.modifiedDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="orderStatus">
        <template #default="scope">
          <el-tag type="primary" disable-transitions>
            {{ scope.row.orderStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="left" header-align="center" prop="remarks" width="180"/>
      <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-if="scope.row.orderStatus === '待确认'">编辑</el-button>
          <el-button link type="primary" icon="EditPen" @click="handleChange(scope.row)" v-if="scope.row.orderStatus === '已确认'
            || scope.row.orderStatus === '到出口港'">变更</el-button>
          <el-button link type="primary" icon="RefreshLeft" @click="handleReturn(scope.row)" v-if="scope.row.orderStatus === '待确认'">退货</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-if="scope.row.orderStatus === '已入库'">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 修改订单对话框 -->
    <el-dialog title="采购订单修改" v-model="open" width="600px" append-to-body>
      <el-form ref="orderMaintainRef" :model="form" :rules="rules" label-width="100px" label-position="top" style="padding-right: 10px">
        <el-row gutter="15">
          <el-col :span="12">
            <el-form-item label="采购订单编号" prop="orderNo">
              <el-input v-model="form.orderNo" disabled/>
            </el-form-item>
            <el-form-item label="采购负责人" prop="responsiblePerson">
              <el-input v-model="form.responsiblePerson" placeholder="请输入采购负责人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交货地点" prop="deliveryAddress">
              <el-select v-model="form.deliveryAddress" placeholder="请选择交货地点" style="width: 100%" @change="handleSelectedAddressChange">
                <el-option
                    v-for="item in addressList"
                    :key="item.code"
                    :label="formatAddress(item)"
                    :value="item.name"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remarks">
          <el-input type="textarea" v-model="form.remarks" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <el-divider content-position="center">订单详情信息</el-divider>

      <el-table :data="orderDetailList" style="margin-top: 15px">
        <el-table-column label="货品批号" align="center" prop="rawProductBatch" width="120"/>
        <el-table-column label="货品名称" align="center" prop="rawProductName" width="100"/>
        <el-table-column label="订购数量" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.quantity"
                             :precision="2" controls-position="right" style="width: 90%;"/>
          </template>
        </el-table-column>
        <el-table-column label="预期到货时间" align="center">
          <template #default="scope">
            <el-date-picker
                v-model="scope.row.expectedDeliveryTime"
                placeholder="请选择时间"
                format="YYYY/MM/DD"
                value-format="YYYY-MM-DD"
                style="width: 90%;"
            />
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="OrderMaintain">
import {
  listPurchaseOrder,
  getPurchaseOrder,
  delPurchaseOrder,
  updatePurchaseOrder,
  returnPurchaseOrder
} from "@/api/purchase/purchaseOrder.js";
import { parseTime } from "@/utils/ruoyi.js";
import {getChangeOrderDetail} from "@/api/purchase/orderDetail.js";
import useUserStore from '@/store/modules/user'
import AMapLoader from "@amap/amap-jsapi-loader";
import {listDictData, listDictDataAll} from "@/api/purchase/DictData.js";

const { proxy } = getCurrentInstance();
const { purchase_order_status } = proxy.useDict('purchase_order_status');
const userRole = ref('');

const orderMaintainList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const orderDetailList = ref([])
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const addressList = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    companyName: null,
    orderStatus: null,
  },
  rules: {
    responsiblePerson: [
      { required: true, message: "负责人不能为空", trigger: "blur" }
    ],
    contactPhone: [
      { required: true, message: "联系电话不能为空", trigger: "blur" }
    ],
    deliveryAddress: [
      { required: true, message: "交货地点不能为空", trigger: "blur" }
    ],
    expectedDeliveryTime: [
      { required: true, message: "预期交货时间不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询订单维护列表 */
function getList() {
  loading.value = true;
  listPurchaseOrder(queryParams.value).then(response => {
    orderMaintainList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
  const query = {type: '收货地址'}
  listDictDataAll(query).then(response => {
    addressList.value = response.data;
  })
  if(useUserStore().roles.length === 0){
    useUserStore().getInfo().then(() => {
      userRole.value = useUserStore().roles[0];
    }).catch(error => {
      console.error('Failed to fetch user info', error);
    });
  }
  userRole.value = useUserStore().roles[0];
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    orderNo: null,
    companyName: null,
    deliveryAddress: null,
    orderTime: null,
    expectedDeliveryTime: null,
    totalAmount: null,
    currencyType: null,
    currencyUnit: null,
    responsiblePerson: null,
    orderStatus: null,
    modifiedDate: null,
    modifiedBy: null,
    remarks: null
  };
  proxy.resetForm("orderMaintainRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.orderNo);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加订单维护";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _orderNo = row.orderNo;
  if(row.orderStatus === '待确认'){
    getChangeOrderDetail(_orderNo).then(response => {
      orderDetailList.value = response.rows;
    })
    getPurchaseOrder(_orderNo).then(response => {
      form.value = response.data;
      open.value = true;
    });
    return;
  }
  proxy.$modal.msgError("只能修改待确认订单！");
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderMaintainRef"].validate(valid => {
    if(valid){
      if (form.value.orderNo != null) {
        form.value.details = orderDetailList.value;
        updatePurchaseOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _orderNos = row.orderNo || ids.value;
  proxy.$modal.confirm('是否确认删除订单维护编号为"' + _orderNos + '"的数据项？').then(function() {
    return delPurchaseOrder(_orderNos);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 退货按钮操作 */
function handleReturn(row) {
  const _orderNo = row.orderNo;
  proxy.$modal.confirm('是否确认退货订单维护编号为"' + _orderNo + '"的数据项？').then(function() {
    return returnPurchaseOrder(_orderNo);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("退货成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('purchaseOrder/export', {
    ...queryParams.value
  }, `orderMaintain_${new Date().getTime()}.xlsx`)
}

function handleChange(order){
  proxy.$router.push({
    path:'/Operator/ChangeDetail',
    query:{
      orderNo: order.orderNo
    }
  });
}

/** 格式化订单交货地点的选择 */
function formatAddress(item) {
  return item.name + " - " + item.person + " - " + item.contact;
}

/** 选择交货地点后为负责人和联系电话赋值 */
function handleSelectedAddressChange(value){
  if(value){
    addressList.value.forEach(item => {
      if(item.name === value){
        form.value.responsiblePerson = item.person;
        form.value.contactPhone = item.contact;
        form.value.destinationLng = item.lng;
        form.value.destinationLat = item.lat;
      }
    })
  }
}

getList();
</script>